package compiladorglc.hash;

public class TabelaDeSimbolos {

	private final static Integer TABLE_SIZE = 128;
	 
    Registro[] table;

    TabelaDeSimbolos() {
          
    	table = new Registro[TABLE_SIZE];
          
    	for (int i = 0; i < TABLE_SIZE; i++)
    		table[i] = null;
    }
    
    public Integer getHashCode(String lexema){

    	Double hashCode = (double) 0;

    	for(Integer i=0;i<lexema.length();i++){
    		hashCode += lexema.charAt(i)*Math.pow((double) 10, (double) i);
    	}
  
    	return hashCode()%TABLE_SIZE;
    }

    /**
     * @description Procura por um lexema na tabela de simbolos
     * retornornando um registro contendo o numero do token e o lexema
     * @param lexema
     * @return Integer
     */
    public Integer procuraLexema(String lexema) {
    	
          Integer hashCode = getHashCode(lexema);
         
          while (table[hashCode] != null && !table[hashCode].getLexema().toUpperCase().equals(lexema.toUpperCase())	){
                hashCode = (hashCode + 1) % TABLE_SIZE;
          }
          
          if (table[hashCode] == null) {
                return -1;
          } else {
                return table[hashCode].getCodigoToken();
          }
    }

    /**
     * @description Inseri novo registro na tabela de simbolos
     * @param codigoToken
     * @param lexema
     */
    public void put(Integer codigoToken, String lexema) {
    	
          Integer hashCode = (getHashCode(lexema) % TABLE_SIZE);
          
          while (table[hashCode] != null && !table[hashCode].getLexema().toUpperCase().equals(lexema.toUpperCase()) )
                hashCode = (hashCode + 1) % TABLE_SIZE;

          table[hashCode] = new Registro(codigoToken, lexema);
    }
}
